package com.chatplus.application.service.pay.impl.wechat;

import com.chatplus.application.client.pay.WeChatPayClient;
import com.chatplus.application.client.pay.domain.request.wechat.WeChatOrderPayRequest;
import com.chatplus.application.client.pay.domain.response.wechat.WechatOrderPayResponse;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.enumeration.SubModeEnum;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 微信支付-H5支付
 */
@Service("WeChatApiService_WECHAT_H5")
public class WeChatPayH5PayService extends WeChatPayApiService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(WeChatPayH5PayService.class);

    @Autowired
    public WeChatPayH5PayService(WeChatPayClient weChatPayClient) {
        super(weChatPayClient);
    }

    @Override
    public WechatOrderPayResponse orderPay(WeChatOrderPayRequest param) {
        try {
            WxPayUnifiedOrderV3Request request = new WxPayUnifiedOrderV3Request();
            request.setMchid(param.getMchId());
            // 通知地址
            request.setNotifyUrl(param.getNotifyUrl());
            request.setTimeExpire(param.getExpireTime());
            // 商户订单号
            request.setOutTradeNo(param.getPayTransactionId());
            request.setAmount(new WxPayUnifiedOrderV3Request.Amount().setTotal(param.getMoney().intValue()));
            // 商品描述
            request.setDescription(param.getSubject());
            //  附加数据
            request.setAttach(SubModeEnum.WECHAT_H5.getValue());
            request.setSceneInfo(
                    new WxPayUnifiedOrderV3Request.SceneInfo()
                            .setPayerClientIp(param.getPayerClientIp())
                            .setH5Info(new WxPayUnifiedOrderV3Request.H5Info().setType(param.getSceneType())));
            request.setMchid(param.getMchId());
            WechatOrderPayResponse response = weChatPayClient.h5Pay(request);
            if (StringUtils.isNotEmpty(param.getReturnUrl())) {
                String h5Url = response.getH5Url();
                h5Url = h5Url + "&redirect_url=" + URLEncoder.encode(param.getReturnUrl(), StandardCharsets.UTF_8);
                response.setH5Url(h5Url);
            }
            return response;
        } catch (Exception e) {
            LOGGER.message("微信支付-H5支付调用失败")
                    .context("request", param)
                    .exception(e).error();
        }
        return null;
    }
}
